<!DOCTYPE html>
<html lang="en">
<head>
  <title>egg-i18n - Born to build better enterprise frameworks and apps</title>
  <meta charset="utf-8">
  <meta name="description" content="index.description">
  <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <link rel="icon" href="/images/favicon.png" type="image/x-icon">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/docsearch.js/2/docsearch.min.css" />
<link rel="stylesheet" href="/css/index.css">

    <script>
    !function(t,e,a,r,c){t.TracertCmdCache=t.TracertCmdCache||[],t[c]=window[c]||
      {_isInit:!0,call:function(){t.TracertCmdCache.push(arguments)},
      start:function(t){this.call('start',t)}},t[c].l=new Date;
      var n=e.createElement(a),s=e.getElementsByTagName(a)[0];
      n.async=!0,n.src=r,s.parentNode.insertBefore(n,s)}
    (window,document,'script','https://tracert.alipay.com/tracert.js','Tracert');
      Tracert.start({
        plugins: [ 'BucName' ],
        spmAPos: 'a454',
        spmBPos: 'b4893',
      });
    </script>
  
</head>
<body>
  <div class="nav" >
  <header>
    <a href="/en/" class="nav-logo leftpadding" alt="egg"><img src="https://zos.alipayobjects.com/rmsportal/VTcUYAaoKqXyHJbLAPyF.svg"></a>
    <ul class="nav-item">
      <li>
        <form id="search-form">
          <input type="text" id="search-query" class="search-query st-default-search-input">
        </form>
      </li>
      <li><a href="/en/intro/" alt="Guide">Guide</a></li><li><a href="/api/" alt="API">API</a></li><li><a href="/en/tutorials/index.html" alt="Tutorials">Tutorials</a></li><li><a href="https://github.com/search?q=topic%3Aegg-plugin&type=Repositories" alt="Plugins">Plugins</a></li><li><a href="https://github.com/eggjs/egg/releases" alt="Release">Release</a></li>
      
      
        <li class="translations">
          <a class="nav-link">中文文档</a>
          <span class="arrow"></span><ul id="dropdownContent" class="dropdown-content"><li><a id="en" href="/en/plugins/i18n.html" style="color: #22ab28">English</a></li><li><a id="zh-cn" href="/zh-cn/plugins/i18n.html" >中文</a></li></ul>
        </li>
      
      <li><iframe src="https://ghbtns.com/github-btn.html?user=eggjs&repo=egg&type=star&count=true" frameborder="0" scrolling="0" width="150px" height="20px"></iframe></li>
    </ul>
    <a id="mobileTrigger" href="#" class="mobile-trigger">
      <ul>
        <li></li>
        <li></li>
        <li></li>
      </ul>
    </a>
  </header>
</div>
  <div id="container" class="container">
    <div class="page-main">
  <article class="markdown-body">
    <h1>egg-i18n</h1>
    <p><a href="https://npmjs.org/package/egg-i18n" target="_blank" rel="noopener"><img src="https://img.shields.io/npm/v/egg-i18n.svg?style=flat-square" alt="NPM version"></a>
<a href="https://travis-ci.org/eggjs/egg-i18n" target="_blank" rel="noopener"><img src="https://img.shields.io/travis/eggjs/egg-i18n.svg?style=flat-square" alt="build status"></a>
<a href="https://codecov.io/github/eggjs/egg-i18n?branch=master" target="_blank" rel="noopener"><img src="https://codecov.io/github/eggjs/egg-i18n/coverage.svg?branch=master" alt="Test coverage"></a>
<a href="https://david-dm.org/eggjs/egg-i18n" target="_blank" rel="noopener"><img src="https://img.shields.io/david/eggjs/egg-i18n.svg?style=flat-square" alt="David deps"></a>
<a href="https://snyk.io/test/npm/egg-i18n" target="_blank" rel="noopener"><img src="https://snyk.io/test/npm/egg-i18n/badge.svg?style=flat-square" alt="Known Vulnerabilities"></a>
<a href="https://npmjs.org/package/egg-i18n" target="_blank" rel="noopener"><img src="https://img.shields.io/npm/dm/egg-i18n.svg?style=flat-square" alt="npm download"></a></p>
<p>可以为你的应用提供多语言的特性</p>
<h2 id="功能"><a class="markdown-anchor" href="#功能">#</a> 功能</h2>
<ul>
<li>支持多种语言独立配置，统一存放在 config/locale/*.js 下（ 兼容<code>config/locales/*.js</code> ）；</li>
<li>提供 Middleware 为 View 提供 <code>__</code>, <code>gettext</code> 函数获取多语言文案；</li>
<li>基于 URL 参数 <code>locale</code> 修改语言显示，同时会记录到 Cookie，下次请求会用 Cookie 里面的语言方案。</li>
</ul>
<h2 id="配置"><a class="markdown-anchor" href="#配置">#</a> 配置</h2>
<p>默认处于关闭状态，你需要在 <code>config/plugin.js</code> 开启它：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// config/plugin.js</span></span><br><span class="line">exports.i18n = &#123;</span><br><span class="line">  enable: <span class="literal">true</span>,</span><br><span class="line">  package: <span class="string">'egg-i18n'</span>,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>你可以修改 <code>config/config.default.js</code> 来设定 i18n 的配置项：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// config/config.default.js</span></span><br><span class="line">exports.i18n = &#123;</span><br><span class="line">  <span class="comment">// 默认语言，默认 "en_US"</span></span><br><span class="line">  defaultLocale: <span class="string">'zh-CN'</span>,</span><br><span class="line">  <span class="comment">// URL 参数，默认 "locale"</span></span><br><span class="line">  queryField: <span class="string">'locale'</span>,</span><br><span class="line">  <span class="comment">// Cookie 记录的 key, 默认："locale"</span></span><br><span class="line">  cookieField: <span class="string">'locale'</span>,</span><br><span class="line">  <span class="comment">// Cookie 默认 `1y` 一年后过期， 如果设置为 Number，则单位为 ms</span></span><br><span class="line">  cookieMaxAge: <span class="string">'1y'</span>,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>其实大部分时候，你只需要修改一下 <code>defaultLocale</code> 设定默认的语言。</p>
<h2 id="编写你的-i18n-多语言文件"><a class="markdown-anchor" href="#编写你的-i18n-多语言文件">#</a> 编写你的 I18n 多语言文件</h2>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// config/locale/zh-CN.js</span></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">  <span class="string">"Email"</span>: <span class="string">"邮箱"</span>,</span><br><span class="line">  <span class="string">"Welcome back, %s!"</span>: <span class="string">"欢迎回来，%s!"</span>,</span><br><span class="line">  <span class="string">"Hello %s, how are you today?"</span>: <span class="string">"你好 %s, 今天过得咋样？"</span>,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// config/locale/en-US.js</span></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">  <span class="string">"Email"</span>: <span class="string">"Email"</span>,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>或者也可以用 JSON 格式的文件：</p>
<figure class="highlight json"><table><tr><td class="code"><pre><span class="line">// config/locale/zh-CN.json</span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">"email"</span>: <span class="string">"邮箱"</span>,</span><br><span class="line">  <span class="attr">"login"</span>: <span class="string">"帐号"</span>,</span><br><span class="line">  <span class="attr">"createdAt"</span>: <span class="string">"注册时间"</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="使用-i18n-函数获取语言文本"><a class="markdown-anchor" href="#使用-i18n-函数获取语言文本">#</a> 使用 I18n 函数获取语言文本</h2>
<p>I18n 为你提供 <code>__</code> (Alias: <code>gettext</code>) 函数，让你可以轻松获得 locale 文件夹下面的多语言文本。</p>
<blockquote>
<p>NOTE: __ 是两个下划线哦！</p>
</blockquote>
<ul>
<li>ctx.__ = function (key, value[, value2, ...]): 类似 util.format 接口</li>
<li>ctx.__ = function (key, values): 支持数组下标占位符方式，如</li>
</ul>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">ctx.__(<span class="string">'&#123;0&#125; &#123;0&#125; &#123;1&#125; &#123;1&#125;'</span>), [<span class="string">'foo'</span>, <span class="string">'bar'</span>])</span><br><span class="line">ctx.gettext(<span class="string">'&#123;0&#125; &#123;0&#125; &#123;1&#125; &#123;1&#125;'</span>), [<span class="string">'foo'</span>, <span class="string">'bar'</span>])</span><br><span class="line">=&gt;</span><br><span class="line">foo foo bar bar</span><br></pre></td></tr></table></figure>
<h3 id="controllers-下的使用示例"><a class="markdown-anchor" href="#controllers-下的使用示例">#</a> Controllers 下的使用示例</h3>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = <span class="function"><span class="keyword">function</span>* (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">this</span>.body = &#123;</span><br><span class="line">    message: <span class="keyword">this</span>.__(<span class="string">'Welcome back, %s!'</span>, <span class="keyword">this</span>.user.name)</span><br><span class="line">    <span class="comment">// 或者使用 gettext，如果觉得 __ 不好看的话</span></span><br><span class="line">    <span class="comment">// message: this.gettext('Welcome back, %s!', this.user.name)</span></span><br><span class="line">    user: <span class="keyword">this</span>.user,</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h3 id="view-文件下的使用示例"><a class="markdown-anchor" href="#view-文件下的使用示例">#</a> View 文件下的使用示例</h3>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">li</span>&gt;</span>&#123;&#123; __('Email') &#125;&#125;: &#123;&#123; user.email &#125;&#125;<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">li</span>&gt;</span></span><br><span class="line">  &#123;&#123; __('Hello %s, how are you today?', user.name) &#125;&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">li</span>&gt;</span></span><br><span class="line">  &#123;&#123; __('&#123;0&#125; &#123;0&#125; &#123;1&#125; &#123;1&#125;'), ['foo', 'bar']) &#125;&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h3 id="修改应用的默认语言"><a class="markdown-anchor" href="#修改应用的默认语言">#</a> 修改应用的默认语言</h3>
<p>你可以用下面几种方式修改应用的当前语言（修改或会记录到 Cookie)，下次请求直接用设定好的语言。</p>
<p>优先级从上到下：</p>
<ul>
<li>query: /?locale=en-US</li>
<li>cookie: locale=zh-TW</li>
<li>header: Accept-Language: zh-CN,zh;q=0.5</li>
</ul>

  </article>
  <aside id="mobileAside" class="toc">
  <div class="mobile-menu">
    <ul>
      <li><a href="/en/intro/" alt="Guide">Guide</a></li><li><a href="/api/" alt="API">API</a></li><li><a href="/en/tutorials/index.html" alt="Tutorials">Tutorials</a></li><li><a href="https://github.com/search?q=topic%3Aegg-plugin&type=Repositories" alt="Plugins">Plugins</a></li><li><a href="https://github.com/eggjs/egg/releases" alt="Release">Release</a></li>
      
      
        <li class="translations">
          <a class="nav-link">中文文档</a>
          <span class="arrow"></span><ul id="dropdownContent" class="dropdown-content"><li><a id="en" href="/en/plugins/i18n.html" style="color: #22ab28">English</a></li><li><a id="zh-cn" href="/zh-cn/plugins/i18n.html" >中文</a></li></ul>
        </li>
      
    </ul>
  </div>
  <dl><dt id="title-Intro" style="cursor: pointer;" class="aside-title">Guide<a id="collapse-icon-Intro" class="icon opend"></a></dt><dd id=panel-Intro><ul><li><a href="/en/intro/index.html" class="menu-link">What is Egg?</a></li><li><a href="/en/intro/egg-and-koa.html" class="menu-link">Egg and Koa</a></li><li><a href="/en/intro/quickstart.html" class="menu-link">Quick Start</a></li><li><a href="/en/tutorials/progressive.html" class="menu-link">Progressive</a></li><li><a href="/en/migration.html" class="menu-link">Migration to 2.x</a></li></ul></dd><dt id="title-Basics" style="cursor: pointer;" class="aside-title">Basis Function<a id="collapse-icon-Basics" class="icon opend"></a></dt><dd id=panel-Basics><ul><li><a href="/en/basics/structure.html" class="menu-link">Directory Structure</a></li><li><a href="/en/basics/objects.html" class="menu-link">Built-in Objects</a></li><li><a href="/en/basics/env.html" class="menu-link">Environment</a></li><li><a href="/en/basics/config.html" class="menu-link">Configuration</a></li><li><a href="/en/basics/middleware.html" class="menu-link">Middleware</a></li><li><a href="/en/basics/router.html" class="menu-link">Router</a></li><li><a href="/en/basics/controller.html" class="menu-link">Controller</a></li><li><a href="/en/basics/service.html" class="menu-link">Service</a></li><li><a href="/en/basics/plugin.html" class="menu-link">Plugin</a></li><li><a href="/en/basics/schedule.html" class="menu-link">Schedule</a></li><li><a href="/en/basics/extend.html" class="menu-link">Extend</a></li><li><a href="/en/basics/app-start.html" class="menu-link">Custom Init</a></li></ul></dd><dt id="title-Core" style="cursor: pointer;" class="aside-title">Core<a id="collapse-icon-Core" class="icon opend"></a></dt><dd id=panel-Core><ul><li><a href="/en/core/development.html" class="menu-link">Development</a></li><li><a href="/en/core/unittest.html" class="menu-link">Unit Testing</a></li><li><a href="/en/core/deployment.html" class="menu-link">Deployment</a></li><li><a href="/en/core/logger.html" class="menu-link">Logger</a></li><li><a href="/en/core/httpclient.html" class="menu-link">HttpClient</a></li><li><a href="/en/core/cookie-and-session.html" class="menu-link">Cookie and Session</a></li><li><a href="/en/core/cluster-and-ipc.html" class="menu-link">Cluster and IPC</a></li><li><a href="/en/core/view.html" class="menu-link">View</a></li><li><a href="/en/core/error-handling.html" class="menu-link">Error Handling</a></li><li><a href="/en/core/security.html" class="menu-link">Security</a></li><li><a href="/en/core/i18n.html" class="menu-link">i18n</a></li></ul></dd><dt id="title-Tutorials" style="cursor: pointer;" class="aside-title">Tutorials<a id="collapse-icon-Tutorials" class="icon opend"></a></dt><dd id=panel-Tutorials><ul><li><a href="/en/tutorials/mysql.html" class="menu-link">MySQL</a></li><li><a href="/en/tutorials/restful.html" class="menu-link">RESTful API</a></li><li><a href="/en/tutorials/passport.html" class="menu-link">Passport</a></li><li><a href="/en/tutorials/socketio.html" class="menu-link">Socket.IO</a></li><li><a href="/en/tutorials/assets.html" class="menu-link">Assets</a></li><li><a href="/en/tutorials/typescript.html" class="menu-link">TypeScript</a></li></ul></dd><dt id="title-Advanced" style="cursor: pointer;" class="aside-title">Advanced<a id="collapse-icon-Advanced" class="icon opend"></a></dt><dd id=panel-Advanced><ul><li><a href="/en/advanced/loader.html" class="menu-link">Loader</a></li><li><a href="/en/advanced/plugin.html" class="menu-link">Plugin Development</a></li><li><a href="/en/advanced/framework.html" class="menu-link">Framework</a></li><li><a href="/en/advanced/cluster-client.html" class="menu-link">Cluster Enhancement</a></li><li><a href="/en/advanced/view-plugin.html" class="menu-link">View Plugin</a></li><li><a href="/en/style-guide.html" class="menu-link">Style Guide</a></li></ul></dd><dt id="title-Community" style="cursor: pointer;" class="aside-title">Community<a id="collapse-icon-Community" class="icon opend"></a></dt><dd id=panel-Community><ul><li><a href="/en/plugins/" class="menu-link">Plugin List</a></li><li><a href="/en/contributing.html" class="menu-link">Contributing</a></li><li><a href="/en/resource.html" class="menu-link">Resource</a></li><li><a href="/en/faq.html" class="menu-link">FAQ</a></li></ul></dd></dl>
</aside>
<script>
var mobileTrigger = document.getElementById('mobileTrigger');
var mobileAside = document.getElementById('mobileAside');

var expandMenu = function(title) {
  // handle icon
  const collapseIcon = document.getElementById('collapse-icon-' + title);
  if (collapseIcon) {
    collapseIcon.className = 'icon opend';
  }
  // handle panelEle
  const panelEle = document.getElementById('panel-' + title);
  if (panelEle) {
    panelEle.className = '';
  }
}

var collapseMenu = function(title) {
  // handle icon
  const collapseIcon = document.getElementById('collapse-icon-' + title);
  if (collapseIcon) {
    collapseIcon.className = 'icon closed';
  }
  // handle panelEle
  const panelEle = document.getElementById('panel-' + title);
  if (panelEle) {
    panelEle.className = 'aside-panel-hidden';
  }
}

mobileAside.onclick = function(e) {
  const targetId = e.target.id;
  if (targetId && (targetId.indexOf('title-') > -1 || targetId.indexOf('collapse-icon-') > -1)) {
    const title = targetId.replace('title-', '').replace('collapse-icon-', '');
    try { 
      // the the browser may have no localStroage or JSON.parse may throw exception.
      const menuInfo = JSON.parse(window.localStorage.getItem('menuInfo'));
        
      // current menu status
      const curClosed = menuInfo[title] ? menuInfo[title].closed : false; // default false

      // change UI
      curClosed ? expandMenu(title) : collapseMenu(title);

      // save menuInfo to localStorage
      menuInfo[title] = { closed: !curClosed } // opposite
      window.localStorage.setItem('menuInfo', JSON.stringify(menuInfo));
    } catch (e) {}
  }
};

mobileTrigger.onclick = function(e) {
  e.preventDefault();
  if (mobileAside.className.indexOf('mobile-show') === -1) {
    mobileAside.className += ' mobile-show';
  } else {
    mobileAside.className = 'toc';
  }
};

(function() {
  // save data to localStorage because the page will refresh when user change the url.
  let menuInfo;
  try { 
    // the the browser may have no localStroage or JSON.parse may throw exception.
    menuInfo = JSON.parse(window.localStorage.getItem('menuInfo'));
    if (!menuInfo) {
      menuInfo = {};
      window.localStorage.setItem('menuInfo', JSON.stringify(menuInfo));
    }
  } catch (e) {
    menuInfo = {}; // default {}
  }

  for (const title in menuInfo) {
    if (menuInfo[title] && menuInfo[title].closed) { // menu in closed status.
      collapseMenu(title);
    } else {
      expandMenu(title);
    }
  }

  // highlight menu
  const pathname = window.location.pathname;
  const selector = `a[href="${pathname}"].menu-link,a[href="${pathname}index.html"].menu-link`;
  const menuItem = mobileAside.querySelector(selector);
  if (menuItem) { menuItem.className += ' highlight'; }
})();
</script>

</div>

  </div>
</body>
<script src="https://cdn.jsdelivr.net/docsearch.js/2/docsearch.min.js"></script>
<script>
docsearch({
  apiKey: '1561de31a86f79507ea00cdb54ce647c',
  indexName: 'eggjs',
  inputSelector: '#search-query',
});
</script>
<div class="cnzz">
<script src="https://s11.cnzz.com/z_stat.php?id=1261142226&web_id=1261142226" language="JavaScript"></script>
</div>

</html>
